package com.rxkj.authen;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.rxkj.entity.sys.UserInfo;
import com.rxkj.service.UserService;
import com.rxkj.utils.DateFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截器 用于处理登陆及权限验证
 * by alex
 * 2022-4-7
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        httpServletResponse.setContentType("text/html;charset=utf-8");
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(RoleLevel.class)) {
            RoleLevel role = method.getAnnotation(RoleLevel.class);
            if (role != null) {
                // 从 http 请求头中取出 token
                String token = httpServletRequest.getHeader("Authorization");
                // 执行 登陆验证
                if (token == null) {
                    Map<String, Object> res = new HashMap<>();
                    res.put("code", 401);
                    res.put("message", "无token，请重新登录！");
                    String jsonstr = JSONObject.toJSONString(res);
                    PrintWriter writer = httpServletResponse.getWriter();
                    httpServletResponse.setStatus(401);
                    httpServletResponse.sendError(401, "请进行登录！");
                    writer.write(jsonstr);
                    return false;
                    //throw new RuntimeException("401");
                }
                // Bearer xxxxxx 截取7以后的
                token = token.substring(7);
                //检查token有效期
                if(DateFormatUtil.isoutexptime(token)){
                    //过期了
                    Map<String, Object> res = new HashMap<>();
                    res.put("code", 401);
                    res.put("message", "登录有效期已过，请重新登陆！");
                    String jsonstr = JSONObject.toJSONString(res);
                    PrintWriter writer = httpServletResponse.getWriter();
                    httpServletResponse.setStatus(401);
                    httpServletResponse.sendError(401, "请进行登录！");
                    writer.write(jsonstr);
                    return false;
                    //throw new RuntimeException("401");
                }
                // 获取 token 中的 user id
                Integer userId;
                try {
                    userId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401");
                }
                UserInfo ui = userService.getUserById(userId);
                if (ui == null) {
                    Map<String, Object> res = new HashMap<>();
                    res.put("code", 401);
                    res.put("message", "用户不存在，请重新登录！");
                    String jsonstr = JSONObject.toJSONString(res);
                    PrintWriter writer = httpServletResponse.getWriter();
                    httpServletResponse.setStatus(401);
                    httpServletResponse.sendError(401, "请进行登录！");
                    writer.write(jsonstr);
                    return false;
                    //throw new RuntimeException("401");
                }
                // 通过密钥生成验证对象 验证 token是否合法
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(ui.getUserPwd())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("401");
                }
                userId = JWT.decode(token).getClaim("id").asInt();
                String uname = JWT.decode(token).getClaim("userName").asString();
                //将userId放入session中
                httpServletRequest.getSession().setAttribute("id",userId);
                httpServletRequest.getSession().setAttribute("userName",uname);
                //权限验证
                //user权限等级
                Integer level = JWT.decode(token).getClaim("roleLevel").asInt();
                //放行要求等级
                Integer require = role.value();
                if (level <= require){
                    return true;
                }else {
                    /*Map<String, Object> res = new HashMap<>();
                    res.put("code", 400);
                    res.put("message", "无此权限进行查看！");
                    String jsonstr = JSONObject.toJSONString(res);
                    PrintWriter writer = httpServletResponse.getWriter();
                    writer.write(jsonstr);*/
                    return false;
                }

            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

}
